/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package report.web;

import com.google.common.base.Splitter;
import com.lhy.report.bean.MigrationDataParam;
import com.lhy.report.split.impl.DefaultTaskMigrationDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @project-name:wiz-sound-ai3
 * @package-name:com.wiz.soundai.crm.controller
 * @author:LiBo/Alex
 * @create-date:2021-09-18 13:40
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/execute/batch")
public class ExecuteBatchDataController {


    @Autowired
    DefaultTaskMigrationDataService defaultTaskMigrationDataService;


    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    
    /**
     * 线索层面的数据迁移机制(根据taskId)
     * @param callTaskIdList
     * @return
     */
    @GetMapping("/migrationByTaskId")
    public Boolean migrationByTaskId(@RequestParam("callTaskId") String callTaskIdList) {
        log.info("migration parameter task Id ：{}",callTaskIdList);
        if(StringUtils.isNotEmpty(callTaskIdList)){
            try {
                MigrationDataParam queryMigrationParam = new MigrationDataParam();
                queryMigrationParam.setTargetBizCodes(Splitter.on(",").omitEmptyStrings().splitToList(callTaskIdList).
                        stream().map(Long::valueOf).collect(Collectors.toList()));
                // 平衡速度机制
                queryMigrationParam.setBalanceRate(Boolean.TRUE);
                queryMigrationParam.setMockOperation(Boolean.FALSE);
                queryMigrationParam.setDataRangeType(MigrationDataParam.MigrationDataRangeType.MIGRATION_TARGET_IDS);
                defaultTaskMigrationDataService.migrationDataProcess(queryMigrationParam);
                log.info("execute process true！");
            } catch (Exception e) {
                log.error("execute process failure！",e);
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }



    @GetMapping("/migrationByDataRange")
    public Boolean migrationByDataRange(@RequestParam("processRateUnit") Long processRateUnit,@RequestParam("allCount") Long allCount) {
        log.info("migration parameter processRateUnit：{} allCount：{} ",processRateUnit,allCount);
        try {
            MigrationDataParam queryMigrationParam = new MigrationDataParam();
            // 平衡速度机制
            queryMigrationParam.setBalanceRate(Boolean.TRUE);
            queryMigrationParam.setMockOperation(Boolean.FALSE);
            queryMigrationParam.setProcessDataUnit(processRateUnit);
            queryMigrationParam.setAllCount(allCount);
            queryMigrationParam.setDataRangeType(MigrationDataParam.MigrationDataRangeType.MIGRATION_DATA_RANGE);
            defaultTaskMigrationDataService.migrationDataProcess(queryMigrationParam);
            log.error("execute process true！");
        } catch (Exception e) {
            log.error("execute process failure！",e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


    /**
     * 线索层面的数据迁移机制(根据时间范围)
     * @param startDate
     * @param endDate
     * @param isMock
     * @param dataStatus
     * @param dataType
     * @return
     */
    @GetMapping("/migrationByRangeTime")
    public Boolean migrationByRangeTime(@RequestParam("startDate") String startDate,
                                        @RequestParam("endDate") String endDate,
                                        @RequestParam("allCount") Long allCount,
                                        @RequestParam(value = "isMock",defaultValue = "0") Integer isMock,
                                        @RequestParam(value = "dataStatus",required = false) Integer dataStatus,
                                        @RequestParam(value = "dataType",required = false) Integer dataType,
                                        @RequestParam(value = "dateSplitIntervalDays",defaultValue = "5") Integer dateSplitIntervalDays) {
        log.info("request paremeter：startDate: {} , endDate : {} {} {}",startDate,endDate,isMock,dataStatus,dataType);
        String startDateTimeStr =  startDate+" 00:00:00",endDateTimeStr = endDate+" 23:59:59";
        LocalDateTime startDateTime = LocalDateTime.from(dateTimeFormatter.parse(startDateTimeStr));
        LocalDateTime endDateTime = LocalDateTime.from(dateTimeFormatter.parse(endDateTimeStr));
        log.info("migration parameter data query condition ：{}",startDateTimeStr,endDateTimeStr);
        MigrationDataParam queryMigrationParam = new MigrationDataParam();
        queryMigrationParam.setDataRangeType(MigrationDataParam.MigrationDataRangeType.MIGRATION_DATE_RANGE);
        queryMigrationParam.setComputeStartTime(startDateTime);
        queryMigrationParam.setAllCount(allCount);
        queryMigrationParam.setComputeEndTime(endDateTime);
        queryMigrationParam.setDateSplitIntervalDays(dateSplitIntervalDays);
        // 平衡速度机制
        queryMigrationParam.setBalanceRate(Boolean.TRUE);
        queryMigrationParam.setMockOperation(isMock.byteValue() == NumberUtils.BYTE_ZERO.intValue());
        try {
            if(Objects.nonNull(dataStatus)){
                queryMigrationParam.setDataStatus(dataStatus.byteValue());
            }
            if(Objects.nonNull(dataType)){
                queryMigrationParam.setDataType(dataType.byteValue());
            }
            defaultTaskMigrationDataService.migrationDataProcess(queryMigrationParam);
        } catch (Exception e) {
            log.error("execute process failure！",e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
